#include "draw2.h"
#include "figStack.h"
#include "read.h"
#include "process.h"

#line 6 "draw2.c"

//int inputFileLength = 0;

int main( int argc, const char * argv[] ) {

    /* Check environment. */
    if ( argc != 2 ) {
        fprintf(stderr, "draw2 %d: error\n", __LINE__);
        exit(EXIT_FAILURE);
    }

    char exec_c[23+1];
    FILE * sketchpad;

    if ( (sketchpad = fopen("Sketchpad.jar", "r")) != NULL )
        strncpy(exec_c, "java -jar Sketchpad.jar", 24);

    else if ( (sketchpad = fopen("sketchpad.jar", "r")) != NULL )
        strncpy(exec_c, "java -jar sketchpad.jar", 24);

    else {
        fprintf(stderr, "draw2 %d: error.\n", __LINE__);
        exit(EXIT_FAILURE);
    }

    int debug = 0;
    FILE * inputFile = fopen(argv[1], "r");
    FILE * outputFile = popen(exec_c, "w");

    if ( !inputFile || !outputFile ) {
        fprintf(stderr, "draw2 %d: error.", __LINE__);
        exit(EXIT_FAILURE);
    }

    char * buff = (char *) malloc(MAXLEN+1);

    if ( buff == NULL ) {
        fprintf(stderr, "malloc() failure.\n");
        exit(EXIT_FAILURE);
    }

    memset(buff, '\0', (MAXLEN+1));

    for ( inputFileLength = 0;      /* Get file length (line count). */
          fgets(buff, MAXLEN+1, inputFile) != NULL;
          inputFileLength++)
        ;

    free(buff);


    /* Holds a line read from a file. */
    Line Lines[inputFileLength];

    /* Holds figure definitions found. */
    FigStack Figures;
    initstack( &Figures, 20 );


    /* Welcome message. */
    printf("%s started on ", argv[0]);
    fflush(NULL);
    system("date");
    printf("Input file: ./%s\n", argv[1]);


    /* Store file. */
    if ( (debug = readFile(Lines, inputFile)) ) {
        fprintf(stderr, "draw2 %d: error.\n", __LINE__);
        exit(EXIT_FAILURE);
    }

    /* Classify each line stored. */
    if ( (debug = classifyLines(Lines)) ) {
        fprintf(stderr, "draw2 %d: error.\n", __LINE__);
        exit(EXIT_FAILURE);
    }

    /* Execute an action depending on the tag for each line. */
    executeCommands( outputFile, Lines, Figures);



    if (pclose(outputFile) == -1) {
        fprintf(stderr, "pclose() failure.\n");
        exit(EXIT_FAILURE);
    }
    fclose(inputFile);

    return 0;
}
